//https://leetcode.cn/problems/swap-nodes-in-pairs/
package codeRandomThoughts.Test24两两交换链表中的节点;

import codeRandomThoughts.utils.ListNode;

//二刷
public class Solution2 {
    //返回值是节点交换后的链表
    public ListNode swapPairs(ListNode head) {
        //递归终止条件
        if (head == null) {
            return null;
        } else if (head.next == null) {
            return head;
        }
        //下面这个不加也是对的 为什么?
        //因为下面的代码已经涵盖了这种情况
        //所以写的时候才会觉得冗余 原来如此
        //else if (head.next.next==null){
        //    ListNode headSwapped = head.next;
        //    head.next.next=head;
        //    head.next=null;
        //    return headSwapped;
        //}

        ListNode swappedList = swapPairs(head.next.next);
        ListNode newHead = head.next;
        head.next.next = head;
        head.next = swappedList;
        return newHead;
    }

    public ListNode swapPairs2(ListNode head) {
        ListNode dummyHead = new ListNode();
        dummyHead.next = head;
        ListNode curr = dummyHead;
        ListNode pre = new ListNode();
        ListNode next = new ListNode();

        //next不为空才能交换
        while (curr.next != null && curr.next.next != null) {
            pre = curr;
            curr = curr.next;
            next = curr.next;

            curr.next = next.next;
            pre.next = next;
            next.next = curr;
        }

        return dummyHead.next;
    }
}
